package com.wdl.report.business.ppv.mvp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.wdl.report.R2;
import com.wdl.report.app.utils.ChartUtils;
import com.wdl.report.app.utils.CodeUtils;
import com.wdl.report.business.ppv.di.component.DaggerReportPpvComponent;
import com.wdl.report.business.ppv.mvp.contract.ReportPpvContract;
import com.wdl.report.business.ppv.mvp.presenter.ReportPpvPresenter;

import com.wdl.report.R;
import com.wdl.report.db.ReportInfo;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;
import me.wdl.component.commonsdk.core.RouterHub;
import me.wdl.component.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/01/2019 21:30
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@Route(path = RouterHub.REPORT_PPVACTIVITY)
public class ReportPpvActivity extends BaseActivity<ReportPpvPresenter> implements ReportPpvContract.View {
    @BindView(R2.id.support_print_view)
    ScrollView print_view;

    @BindView(R2.id.chart_01)
    LineChart chart_01;

    @BindView(R2.id.pdjrssl)
    TextView pdjrssl;
    @BindView(R2.id.sscxsj)
    TextView sscxsj;

    @BindView(R2.id.title_reprot)
    EditText et_title;

    @BindView(R2.id.input_name)
    EditText et_name;

    @BindView(R2.id.input_sex)
    EditText et_sex;

    @BindView(R2.id.input_age)
    EditText et_age;


    private LoadingDialog loadingDialog;
    private RxPermissions rxPermissions;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerReportPpvComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_report_ppv; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        rxPermissions = new RxPermissions(this);

        ChartUtils.initChart(chart_01);

        String reprotTitle = RxSPTool.getString(this, TITLE_SP);
        if (reprotTitle == null || reprotTitle.length() == 0)
            showEditTitleDialog(this);
        else
            et_title.setText(reprotTitle);

        showAjust();

        mPresenter.initReceiveListener();
    }

    @Override
    public void showLoading() {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("努力操作中...");

        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (loadingDialog != null)
            loadingDialog.close();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R2.id.print_upload)
    public void clickUpload() {
        showOrHideAjustCursor(false);

        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        mPresenter.upload(ReportPpvActivity.this, print_view);
                    } else {
                        RxToast.error("存储权限异常");
                    }
                });

        saveAjust();
    }

    @OnClick(R2.id.search_setting)
    public void clickSearch() {
        Utils.navigation(this, RouterHub.REPORT_SEARCHACTIVITY);
    }

    @OnClick(R2.id.print_receive)
    public void clickReceive() {
        clearChart();

        mPresenter.startReceiveCmd();
    }


    @OnClick(R2.id.print_dyj)
    public void clickPrint() {
        showOrHideAjustCursor(false);

        mPresenter.print(this, print_view);

        saveAjust();
    }

    @OnClick(R2.id.print_change)
    public void clickChange() {
        showChooseModel(this);
    }

    @OnClick(R2.id.print_setting)
    public void clickSetting() {
        showEditTitleDialog(this);
    }

    private String[] stocks = {"PP", "PPA", "PPV"};

    private void showChooseModel(Activity context) {
        MaterialDialog.Builder mBuilder = new MaterialDialog.Builder(context);
        mBuilder.title("选择模式");
        mBuilder.titleGravity(GravityEnum.CENTER);
        mBuilder.titleColor(Color.parseColor("#000000"));
        mBuilder.items(stocks);
        mBuilder.autoDismiss(true);
        mBuilder.itemsCallback((dialog, itemView, position, text) -> {
            if ("PP".equals(text)) {
                Utils.navigation(context, RouterHub.REPORT_PPACTIVITY);
                clearChart();
            } else if ("PPA".equals(text)) {
                Utils.navigation(context, RouterHub.REPORT_PPAACTIVITY);
                clearChart();
            } else if ("PPV".equals(text)) {
//                Utils.navigation(context,RouterHub.REPORT_PPVACTIVITY);
            }
        });
        MaterialDialog mMaterialDialog = mBuilder.build();
        mMaterialDialog.show();
    }

    @Override
    public void uploadSuccess(String url) {
        MaterialDialog show = new MaterialDialog.Builder(ReportPpvActivity.this)
                .customView(R.layout.dialog_show_code, true)
                .show();

        CodeUtils.showErCode(show.getCustomView().findViewById(R.id.img_ercode), url);
    }

    @Override
    public void showChart(List<Entry> entries) {
        runOnUiThread(() -> ChartUtils.addLineFillData(chart_01, entries));
    }

    @Override
    public void showTotalData(List<Integer> datas) {
        runOnUiThread(() -> {
            pdjrssl.setText(String.valueOf(datas.get(0)) + "mmHg");
            sscxsj.setText(String.valueOf(datas.get(1)) + "秒");
        });
    }

    @Override
    public ReportInfo getWrapReportInfo() {
        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setReportType(3);
        reportInfo.setName(et_name.getText().toString().trim());
        reportInfo.setSex(et_sex.getText().toString().trim());
        reportInfo.setAge(et_age.getText().toString().trim());
        reportInfo.setReportTime(new Date());
        return reportInfo;
    }

    private static final String TITLE_SP = "ppv_report";

    private void showEditTitleDialog(Activity context) {
        new MaterialDialog.Builder(context)
                .title("请自主输入报告标题")
                .inputType(InputType.TYPE_CLASS_TEXT)
                .input("标题", null, (dialog, input) -> {
                    String title = input.toString();
                    if (title != null && title.length() > 0) {
                        et_title.setText(title);
                        RxSPTool.putString(context, TITLE_SP, input.toString());
                    }
                })
                .positiveText("确定")
                .show();
    }


    @BindView(R2.id.input_ajust)
    EditText et_ajust;

    @BindView(R2.id.input_date)
    EditText et_date;

    private void showOrHideAjustCursor(boolean show) {
        et_ajust.setCursorVisible(show);
        et_age.setCursorVisible(show);
        et_name.setCursorVisible(show);
        et_sex.setCursorVisible(show);
        et_date.setCursorVisible(show);
    }

    @OnTouch({R2.id.input_ajust, R2.id.input_name, R2.id.input_sex, R2.id.input_age,R2.id.input_date})
    public boolean onTouch(View v, MotionEvent event) {
        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            showOrHideAjustCursor(true);// 再次点击显示光标
        }
        return false;
    }

    private static final String AJUST_SP = "ppv_report_ajust";

    private void saveAjust() {
        String trim = et_ajust.getText().toString().trim();
        if (trim != null && trim.length() > 0) {
            RxSPTool.putString(this, AJUST_SP, trim);
        }
    }

    private void showAjust() {
        String string = RxSPTool.getString(this, AJUST_SP);
        if (string != null && string.length() > 0) {
            et_ajust.setText(string);
        }
    }

    private void clearChart() {
        ChartUtils.resetLinechart(chart_01);
    }
}
